from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from apps.goods.models import SPU
from apps.meiduo_admin.serializers.spu import SpuSimpleSerializer, SpuSerializer, BrandSerializer
from apps.meiduo_admin.utils.pagination import MeiduoPagination
from rest_framework.viewsets import ModelViewSet
from apps.goods.models import Brand, GoodsCategory
from apps.meiduo_admin.serializers.spu import FirstCategorySerializer, SecondCategorySerializer


class SpuSimpleView(ListAPIView):
    queryset = SPU.objects.all()
    serializer_class = SpuSimpleSerializer


class SpuViewSet(ModelViewSet):
    queryset = SPU.objects.all()
    serializer_class = SpuSerializer
    pagination_class = MeiduoPagination


class BrandView(ListAPIView):
    queryset = Brand.objects.all()
    serializer_class = BrandSerializer


class FirstView(ListAPIView):
    queryset = GoodsCategory.objects.filter(parent__isnull=True)
    serializer_class = FirstCategorySerializer


class SecondView(ListAPIView):
    def get_queryset(self):
        pk = self.kwargs.get('pk')
        queryset = GoodsCategory.objects.filter(parent=pk)
        return queryset

    serializer_class = SecondCategorySerializer


class ImageView(APIView):
    def post(self, request):
        image = request.data.get('image')

        # 上传图片
        image_client = Fdfs_client(settings.FDFS_CLIENT_CONF)
        data = image_client.upload_by_buffer(image.read())
        image_name = data.get('Remote file_id')

        return Response({'img_url': settings.FDFS_BASE_URL + image_name})
